import { useEffect, useRef, useState } from "react";
import styles from "./index.module.less";
import { ProForm, ProFormInstance } from "@ant-design/pro-components";
import { Affix, Button, ConfigProvider, Flex, Space, message } from "antd";
import BasicInfo from "./components/BasicInfo";
import ProductInfo from "./components/ProductInfo";
import SaleInfo from "./components/SaleInfo";
import GraphicDescription from "./components/GraphicDescription";
import { useNavigate } from "react-router-dom";
import { CheckCircleOutlined } from "@ant-design/icons";
import { MAIN_PRIMARY_COLOR } from "@/enums";
import { omit, map, isEmpty } from "lodash";
import useUrl from "@/hooks/useUrl";
import { useRequest } from "ahooks";
import { getProductDetail, saveProductApi } from "@/api/modules/product";
import { RESULT_CODES } from "@/api/helper/ResultCode";
import Loading from "@/components/Loading";
import dayjs from "dayjs";
//表情符号正则表达式
// eslint-disable-next-line no-misleading-character-class
// 表情符号的正则表达式
export const emojiRegex =
	/[\u{1F600}-\u{1F64F}\u{1F300}-\u{1F5FF}\u{1F680}-\u{1F6FF}\u{1F700}-\u{1F77F}\u{1F780}-\u{1F7FF}\u{1F800}-\u{1F8FF}\u{1F900}-\u{1F9FF}\u{1FA00}-\u{1FA6F}\u{1FA70}-\u{1FAFF}\u{2600}-\u{26FF}\u{2700}-\u{27BF}]/gu;
// 换行符的正则表达式
export const newlineRegex = /[\r\n]+/g;
//换行符号正则表达式

export default () => {
	const formRef = useRef<ProFormInstance>();
	const { navigate, query } = useUrl();
	const product_id = query.get("id");
	const isView = query.get("isView") == 1;
	const [isEdit, setIsEdit] = useState<any>(!isView);
	const { loading, runAsync } = useRequest(saveProductApi, { manual: true });
	const { loading: loadingDetail, runAsync: getDetailRunAsync, data } = useRequest(getProductDetail, { manual: true });

	const DETAIL_DATA = data?.data || {};

	useEffect(() => {
		if (product_id)
			getDetailRunAsync({ product_id }).then((res: any) => {
				if (res?.code === RESULT_CODES.SUCCESS) {
					const data = res?.data ?? {};
					const isFree = data?.service_shipping?.shipping_fee === 0;
					const sales = map(data?.sales_specs_list, i => ({
						...omit(i, "format_price"),
						price: i?.format_price
					}));
					const InitialData = {
						...data,
						product_origin_address: data?.service_attribute?.product_origin_address,
						product_storage_conditions: data?.service_attribute?.product_storage_conditions,
						production_license: data?.service_information?.production_license,
						manufacturer_name: data?.service_information?.manufacturer_name,
						manufacturer_address: data?.service_information?.manufacturer_address,
						manufacturer_contact: data?.service_information?.manufacturer_contact,
						shipping_fee: isFree ? 0 : 1,
						shipping_fee_num: isFree ? undefined : Number(data?.service_shipping?.format_shipping_fee),
						timelines_id: data?.service_timelines?.timelines_id,
						aftersales_options: map(data?.service_aftersales, "aftersales_option_id"),
						sales_specs: isEmpty(sales) ? [{}] : sales
					};

					formRef.current?.setFieldsValue(InitialData);
				}
			});
	}, []);

	useEffect(() => {
		if (!product_id) formRef.current?.resetFields();
	}, [product_id]);

	const handleValuesChange = (changeValue: any) => {
		if (Object.hasOwn(changeValue, "product_name") && typeof changeValue.product_name === "string") {
			const newName = changeValue.product_name.replace(emojiRegex, "").replace(newlineRegex, "");
			formRef.current?.setFieldValue("product_name", newName);
		}
	};

	const handleSubmit = (type: "add" | "edit" | "draft") => {
		const values = formRef.current?.getFieldsFormatValue?.();
		console.log(values, "<=============values");
		const requestData = {
			...omit(values, [
				"shipping_fee_num",
				"production_license",
				"manufacturer_name",
				"manufacturer_address",
				"manufacturer_contact"
			]),
			product_attributes: {
				product_origin_address: values.product_origin_address,
				product_storage_conditions: values.product_storage_conditions
			},
			product_information: {
				production_license: values.production_license,
				manufacturer_name: values.manufacturer_name,
				manufacturer_address: values.manufacturer_address,
				manufacturer_contact: values.manufacturer_contact
			},
			shipping_fee: values.shipping_fee == 1 ? values.shipping_fee_num : 0,
			product_id
		};
		const callback = () => {
			runAsync(requestData, type).then((res: any) => {
				if (res?.code === RESULT_CODES.SUCCESS) {
					message.success(product_id ? "保存成功" : "创建成功");
					handleBack();
				}
			});
		};
		if (type === "draft") {
			callback();
			return;
		}
		formRef.current?.validateFieldsReturnFormatValue?.().then(() => {
			callback();
		});
	};

	const handleBack = () => {
		if (isView) {
			setIsEdit(false);
			return;
		}
		navigate("/products");
	};

	return (
		<ConfigProvider
			theme={{
				components: {
					Radio: {
						wrapperMarginInlineEnd: 60
					},
					Checkbox: {
						marginXS: 60,
						borderRadiusSM: 50
					}
				}
			}}
		>
			<Loading isHeight100 loading={loadingDetail}>
				<div className={styles.container}>
					<ProForm
						disabled={!isEdit}
						colon={false}
						submitter={false}
						formRef={formRef}
						layout="horizontal"
						onValuesChange={handleValuesChange}
						labelCol={{ span: 4 }}
					>
						<Space direction="vertical" size={18} className={styles.space}>
							<BasicInfo />
							<ProductInfo />
							<SaleInfo isView={!isEdit} />
							<GraphicDescription isView={!isEdit} />
						</Space>
					</ProForm>
					{isEdit ? (
						<Affix offsetBottom={0}>
							<Flex justify="center" className={styles.btns}>
								<Space size={10}>
									<Button ghost type="primary" onClick={() => handleBack()}>
										{product_id ? "取消" : "取消创建"}
									</Button>
									{/* <Button loading={loading} ghost type="primary" onClick={() => handleSubmit("draft")}>
											保存草稿
										</Button> */}
									<Button loading={loading} type="primary" onClick={() => handleSubmit(product_id ? "edit" : "add")}>
										{product_id ? "保存" : "创建商品"}
									</Button>
									{product_id && DETAIL_DATA?.updated_at && (
										<Space size={10}>
											<CheckCircleOutlined style={{ color: MAIN_PRIMARY_COLOR }} />
											<span style={{ color: "#000" }}>
												最后保存于{dayjs(DETAIL_DATA?.updated_at).format("YYYY-MM-DD HH:mm:ss")}
											</span>
										</Space>
									)}
								</Space>
							</Flex>
						</Affix>
					) : (
						<Affix offsetBottom={0}>
							<Flex justify="center" className={styles.btns}>
								<Space size={10}>
									<Button ghost type="primary" onClick={() => navigate(-1)}>
										返回
									</Button>
									<Button type="primary" onClick={() => setIsEdit(true)}>
										编辑
									</Button>
								</Space>
							</Flex>
						</Affix>
					)}
				</div>
			</Loading>
		</ConfigProvider>
	);
};
